/** Ajax请求异常处理全局设置 */
$.ajaxSetup({
    complete: function (xhr, status) {
        switch (xhr.status) {
            case 404:
                top.location.href = "/login";
                break;
            case 403:
                alert("权限不足！");
                break;
            case 500:
                alert("server 500 error");
                break;
            case 520:
                top.location.href = "/login";
                break;
        }
    }
});
/**
 * 基于jQuery扩展，获取form表单数据为JS对象
 * @returns {{}}
 */
$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

/**
 * 格式化金额，整数部分用逗号分隔，保留两位小数
 * @param num
 * @param row
 * @param index
 * @returns {string}
 */
function formatMoney(num, row, index) {
    if (!num) {
        return "";
    }
    var parts;
    // 判断是否为数字
    if (!isNaN(parseFloat(num)) && isFinite(num)) {
        // 把类似 .5, 5. 之类的数据转化成0.5, 5, 为数据精度处理做准, 至于为什么
        // 不在判断中直接写 if (!isNaN(num = parseFloat(num)) && isFinite(num))
        // 是因为parseFloat有一个奇怪的精度问题, 比如 parseFloat(12312312.1234567119)
        // 的值变成了 12312312.123456713
        num = Number(num);
        // 处理小数点位数
        num = num.toFixed(2).toString();
        // 分离数字的小数部分和整数部分
        parts = num.split('.');
        // 整数部分加[separator]分隔, 借用一个著名的正则表达式
        parts[0] = parts[0].toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + (','));
        return parts.join('.');
    }
    return NaN;
}

/**
 * 添加cookie
 * @param {string} name   cookie名称
 * @param {string} value  cookie值
 * @param {string} hours  cookie失效小时
 */
function addCookie(name, value, hours) {
    var str = name + "=" + escape(value);
    if (objHours > 0) {//为时不设定过期时间，浏览器关闭时cookie自动消失
        var date = new Date();
        var ms = hours * 3600 * 1000;
        date.setTime(date.getTime() + ms);
        str += "; expires=" + date.toGMTString();
    }
    document.cookie = str;
}

/**
 * 根据name获取cookie
 * @param name
 * @returns {string}
 */
function getCookieByName(name) {
    var cookieArray = document.cookie.split("; "); //得到分割的cookie名值对
    for (var i = 0; i < cookieArray.length; i++) {
        var arr = cookieArray[i].split("=");       //将名和值分开
        if (arr[0] == name)return unescape(arr[1]); //如果是指定的cookie，则返回它的值
    }
    return "";
}

/**
 * 删除cookie
 * @param name
 */
function delCookie(name) {
    document.cookie = name + "=;expires=" + (new Date(0)).toGMTString();
}

/**
 * 获取工程的ContextPath
 * @returns {string}
 */
function getContextPath() {
    var pathName = document.location.pathname;
    var index = pathName.substr(1).indexOf("/");
    var result = pathName.substr(0, index + 1);
    return result;
}

/**
 * 获取服务的根路径
 * @returns {string}
 */
function getBasePath() {
    var obj = window.location;
    var contextPath = obj.pathname.split("/")[1];
    return obj.protocol + "//" + obj.host;
}

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)return unescape(r[2]);
    return null;
}

//关闭对话框操作
function closeDialog(dialog) {
    $("#" + dialog).dialog('close');
}

/**
 * 获取YYYY-MM-DD格式表示的当前日期
 *
 * @returns {string}
 */
function getCurrentDate() {
    var date = new Date();
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    var d = date.getDate();
    return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d);
}

/*
 * 日期格式化 格式为:YYYY-MM-DD
 * @author wangxiong
 */
/**
 * 返回特定格式的日期字串。
 *
 * @param pattern 返回的日期字串样式，例如 yyyy-mm-dd HH:MM:SS sss 返回 2009-11-10 09:40:58 456
 *      y : 年
 *      m : 月
 *      d : 月里的天（1-31）
 *      H : 天里的小时（0-23）
 *      M : 小时里的分钟（0-59）
 *      S : 秒
 *      s : 毫秒
 */
Date.prototype.format = function (pattern) {
    var year, month, day, hour, min, sec, ms, isCn = false;
    if (pattern.indexOf('年') >= 0 || pattern.indexOf('月') >= 0
        || pattern.indexOf('日') >= 0 || pattern.indexOf('号') >= 0) {
        isCn = true;
    }

    year = this.getFullYear();
    month = this.getMonth() + 1;
    day = this.getDate();
    hour = this.getHours();
    min = this.getMinutes();
    sec = this.getSeconds();
    ms = this.getMilliseconds();

    pattern = pattern.replace('yyyy', year);
    pattern = pattern.replace('mm', (isCn || month > 9) ? month : ('0' + month));
    pattern = pattern.replace('dd', (isCn || day > 9) ? day : ('0' + day));

    pattern = pattern.replace('HH', (isCn || hour > 9) ? hour : ('0' + hour));
    pattern = pattern.replace('MM', min > 9 ? min : ('0' + min));
    pattern = pattern.replace('SS', sec > 9 ? sec : ('0' + sec));

    pattern = pattern.replace('sss', (ms > 99 ? ms : (ms > 9 ? ('0' + ms) : ('00' + ms))));

    return pattern;
}

function formatDate(millisecond, patternType) {
    if (millisecond == null) {
        return "";
    }
    var pattern = 'yyyy-mm-dd HH:MM:SS';
    switch (patternType) {
        case 1:
            pattern = 'yyyy-mm-dd HH:MM';
            break;
        case 2:
            pattern = 'yyyy-mm-dd';
            break;
        case 3:
            pattern = 'mm-dd HH:MM';
            break;
    }
    return new Date(millisecond * 1000).format(pattern);
}

function dateRender(val, row, index) {
    return formatDate(val, "yyyy-mm-dd HH:MM:SS")
}

//格式化日期:显示YYYY-MM
function myformatter(date) {
    //获取年份
    var y = date.getFullYear();
    //获取月份
    var m = date.getMonth() + 1;
    return y + '-' + m;
}
/**
 * 获取状态信息
 * @param main
 * @param child
 * @returns {*}
 */
function getStatusValue(main, child) {
    var result = '未知';
    if (dict === null || main === null || child === null) {
        return result;
    }
    var dictJson = $.parseJSON(dict);
    if (!dictJson.hasOwnProperty(main)) return result;
    for (var i = 0; i < dictJson[main].length; i++) {
        if (dictJson[main][i].hasOwnProperty(child)) return dictJson[main][i][child];
    }
    return result;
}

/**
 * 时间戳转换(支持ie)
 * @param day
 * @returns {number}
 */
function getTime(day){
    re = /(\d{4})(?:-(\d{1,2})(?:-(\d{1,2}))?)?(?:\s+(\d{1,2}):(\d{1,2}):(\d{1,2}))?/.exec(day);
    return new Date(re[1],(re[2]||1)-1,re[3]||1,re[4]||0,re[5]||0,re[6]||0).getTime()/1000;
}

(function () {
    function Map() {
        this.elements = new Array();
        this.size = function() {
            return this.elements.length;
        }

        this.isEmpty = function() {
            return (this.elements.length < 1);
        }

        this.clear = function() {
            this.elements = new Array();
        }

        this.put = function(_key, _value) {
            if (!this.containsKey(_key))
                this.elements.push({key : _key,value : _value});
        }

        this.remove = function(_key) {
            var bln = false;
            try {
                for (i = 0; i < this.elements.length; i++) {
                    if (this.elements[i].key === _key) {
                        this.elements.splice(i, 1);
                        return true;
                    }
                }
            } catch (e) {
                bln = false;
            }
            return bln;
        }

        this.get = function(_key) {
            try {
                for (i = 0; i < this.elements.length; i++) {
                    if (this.elements[i].key === _key) {
                        return this.elements[i].value;
                    }
                }
            } catch (e) {
                return null;
            }
        }

        this.element = function(_index) {
            if (_index < 0 || _index >= this.elements.length) {
                return null;
            }
            return this.elements[_index];
        }

        this.containsKey = function(_key) {
            var bln = false;
            try {
                for (i = 0; i < this.elements.length; i++) {
                    if (this.elements[i].key === _key) {
                        bln = true;
                    }
                }
            } catch (e) {
                bln = false;
            }
            return bln;
        }

        this.containsValue = function(_value) {
            var bln = false;
            try {
                for (i = 0; i < this.elements.length; i++) {
                    if (this.elements[i].value === _value) {
                        bln = true;
                    }
                }
            } catch (e) {
                bln = false;
            }
            return bln;
        }

        this.values = function() {
            var arr = new Array();
            for (i = 0; i < this.elements.length; i++) {
                arr.push(this.elements[i].value);
            }
            return arr;
        }

        this.keys = function() {
            var arr = new Array();
            for (i = 0; i < this.elements.length; i++) {
                arr.push(this.elements[i].key);
            }
            return arr;
        }
    }

    function getTreeStructureNodes(opts) {
        var defaultOptions = {items:[], id:"nodeId", lay_is_open:"true",isMenu:false};
        defaultOptions = $.extend(defaultOptions, opts);
        var map = new Map();
        for(var i = 0; i < opts.items.length; i++){
            var item = defaultOptions.items[i];
            if(defaultOptions.isMenu) {
                if(item.typeNode &&  !("03" == item.typeNode)){
                    continue;
                }
            }
            item.id = item[defaultOptions.id];
            map.put(item.id, item);
        }

        var tree = new Array();
        for(var j = 0; j < opts.items.length; j++){
            var item = defaultOptions.items[j];
            if(item.pid){
                var pid = item.pid;
                delete item.pid;
                item.pId = pid;
            }
            item.spread = true;
            item.name = item.nameNode;
            var parent = map.get(item.pId);
            if(parent == null){
                item.children = new Array();
                tree.push(item);
            }else {
                var children = parent.children;
                if(children == null){
                    parent.children = new Array();
                }
                parent.children.push(item);
            }
        }
        return tree;
    }

    function setTreeNodeChecked(treeNodes, ownCheckedTreeNodes) {
        if(!ownCheckedTreeNodes || ownCheckedTreeNodes.length == 0){
            return treeNodes;
        }

        for(var i = 0 ; i < treeNodes.length; i++){
            var node = treeNodes[i];
            for(var m in ownCheckedTreeNodes){
                var object = ownCheckedTreeNodes[m];
                if(object.id == node.id){
                    node.checked = true;
                    break;
                }
            }
        }
    }
    window.treeStructure = {};
    treeStructure.getTreeStructureNodes = getTreeStructureNodes; //get tree structure
    treeStructure.setTreeNodeChecked = setTreeNodeChecked; // set tree node checked
})();